package com.yc.system.service.impl;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.jfinal.config.Routes;
import com.yc.framework.config.CustomFloatDeserializer;
import com.yc.framework.utils.DateTools;
import com.yc.framework.utils.DateUtil;
import com.yc.system.dto.ChangeOrder;
import com.yc.system.dto.OrderDto;
import com.yc.system.dto.UserDto;
import com.yc.system.entity.Book;
import com.yc.system.entity.BookCartLike;
import com.yc.system.entity.BookOrder;
import com.yc.system.entity.User;
import com.yc.system.mapper.BookCartLikeMapper;
import com.yc.system.mapper.BookMapper;
import com.yc.system.mapper.BookOrderMapper;
import com.yc.system.mapper.UserMapper;
import com.yc.system.service.IBookCartLikeService;
import com.yc.system.service.IBookOrderService;
import com.yc.framework.baseClass.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yc.framework.baseClass.R;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeoutException;


/**
 * <p>
 * 订单交易 服务实现类
 * </p>
 *
 * @author 1850140986@qq.com
 * @since 2022-12-06
 */

@Service
public class BookOrderServiceImpl extends BaseServiceImpl<BookOrderMapper,BookOrder> implements IBookOrderService {

    @Autowired
    public BookMapper bookMapper;

    @Autowired
    public BookOrderMapper bookOrderMapper;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public BookCartLikeMapper bookCartLikeMapper;

    @Autowired
    public IBookCartLikeService iBookCartLikeService;
    /**
    * 分页查询实体列表
    * @param model 查询参数
    * @return 查询结果
    */
    @Override
    public R list( BookOrder model){
        IPage<BookOrder> page = new Page<>(model.getPageNum(),model.getPageSize());
        QueryWrapper<BookOrder> wrapper = new QueryWrapper<>();
         initCondition(wrapper);
        setParam(wrapper,model);
         IPage<BookOrder> px = page(page,wrapper);
        return R.ok().put("data",px.getRecords()).put("total", px.getTotal());
    }

    @Override
    public List<BookOrder> getOrderListByIssureId(int userId) {
        return bookOrderMapper.getOrderListByIssureId(userId);
    }

    @Override
    public int getCountByIssureId(int userId) {
        return getOrderListByIssureId(userId).size();
    }

    @Override
    public int getGoodNumByIssureId(int userId) {
        return getOrderListByIssureId(userId).size();
    }

    @Override
    public R getOrderListByUserId(int userId) {
        return R.ok().put("orderList",bookOrderMapper.getOrderListByUserId(userId));
    }

    @Override
    public R getOrderListByIssuerId(int ssuerId) {
        return R.ok().put("orderList",bookOrderMapper.getOrderListByIssureId(ssuerId));
    }

    @Override
    public R addOrder(BookOrder bookOrder) {
        //订单号
        long maxNum=bookOrderMapper.getMaxOrderNum();
//        System.out.println("---------------------");
//        System.out.println("maxNum:"+maxNum);
        if(maxNum!=0){
            bookOrder.setOrderNum(String.valueOf(maxNum+1));
        }else{
            bookOrder.setOrderNum("100000000000");
        }

        bookOrder.setOrderStatus(1);
        R flog=saveModel(bookOrder);
        if(((BookOrder)flog.get("data")).getOrderId()!=0){
//            System.out.println("saveOrder:"+bookOrder);
            BookCartLike bookCartLike=new BookCartLike();
            bookCartLike.setBookId(bookOrder.getBookId());
            bookCartLike.setCartNum(bookOrder.getQuantity());
            int j=bookMapper.changeQuantity(bookCartLike);
            return R.ok().put("bookOrder",bookOrder);
        }else{
            return R.err();
        }


    }

    @Override
    public R updataOrder(BookOrder bookOrder) {
        int updateFlog = bookOrderMapper.updateOrder(bookOrder);
        return R.ok().put("updateFlog",updateFlog).put("bookOrder",bookOrder);
    }

    @Override
    public R getOrderListByPageUserId(BookOrder findByPage) {
        IPage<BookOrder> page = new Page<>(findByPage.getPageNum() ,findByPage.getPageSize());
        List<BookOrder> bookOrders=bookOrderMapper.getBooksByPageRandom(page, findByPage.getUserId());


        List<OrderDto> orderList=new ArrayList<>();
        for (BookOrder order :bookOrders){
            OrderDto orderDto=(OrderDto) order;
            Book book=bookMapper.getBookByBookId(orderDto.getBookId());
            orderDto.setBookName(book.getBookName());
            orderDto.setCoverPhoto(book.getCoverPhoto());
            orderDto.setIsbn(book.getIsbn());
            orderDto.setAuthor(book.getAuthor());
            User user=userMapper.getUserByUserId(book.getUserId());
            orderDto.setIssuerName(user.getUsername());
            orderDto.setIssuerId(user.getUserId());
            orderDto.setAddress(user.getAddress());
            orderList.add(orderDto);
        }
        return R.ok().put("orderList",orderList);

    }

    @Override
    public R getOrders(OrderDto orderDto){
        IPage<OrderDto> page=new Page<>(orderDto.getPageNum(),orderDto.getPageSize());

//        模式： 消费者 Consumers, 商家 merchants
        String model=orderDto.getModel();
//        订单状态：1待付款  2待商家确认 3待商家确认交货 4待确认收货 5待评论 6退货退款中 7已签收 8已退货退款 9已取消 10商家取消 11商家确认退货
        if(model.equals("Consumers")){
            return R.ok().put("orderList",bookOrderMapper.getOrders(page,orderDto.getUserId())).put("total",bookOrderMapper.getOrdersTotal(orderDto.getUserId()));
        }else{
            return R.ok().put("orderList",bookOrderMapper.getOrdersToStore(page,orderDto.getUserId())).put("total",bookOrderMapper.getOrdersToStoreTotal(orderDto.getUserId()));
        }

//        return R.ok().put("orderList",bookOrderMapper.getOrders(page,orderDto.getUserId()));
    }

    @Override
    public R changeOrderStatus(OrderDto orderDto) {

        return R.ok().put("data",bookOrderMapper.changeOrderStatus(orderDto.getOrderId(),orderDto.getOrderStatus()));
    }

    @Override
    @Transactional
    public R addOrdersByCart(List<BookCartLike> orderDto) {
        orderDto.forEach(cart ->{
            int cartId=cart.getClId();
            BookCartLike bookCartLike=bookCartLikeMapper.getOneById(cartId);
            BookOrder bookOrder=new BookOrder();
            bookOrder.setQuantity(bookCartLike.getCartNum());
            bookOrder.setBookId(bookCartLike.getBookId());
            bookOrder.setOrderStatus(1);
            bookOrder.setOrderCreateTime(DateTools.parseDate(DateTools.getNowDate()));
            bookOrder.setUserId(bookCartLike.getUserId());
            Book book=bookMapper.getBookByBookId(bookCartLike.getBookId());
            bookOrder.setPrice(book.getPrice());
            bookOrder.setMoney(Math.round(book.getPrice() * bookCartLike.getCartNum()  * 100) / 100f);
            //订单号
            long maxNum=bookOrderMapper.getMaxOrderNum();
            if(maxNum!=0){
                bookOrder.setOrderNum(String.valueOf(maxNum+1));
            }else{
                bookOrder.setOrderNum("100000000000");
            }

            R flog=saveModel(bookOrder);
//            if(((BookOrder)flog.get("data")).getOrderId()==0){
//                try {
//                    throw new TimeoutException();
//                } catch (TimeoutException e) {
//                    e.printStackTrace();
//                }
//            }
            int j=bookMapper.changeQuantity(bookCartLike);
            iBookCartLikeService.deleteCartById(cartId);

        });
        return R.ok();
    }

    @Override
    public R changeOrder(ChangeOrder changeOrder) {
//        消费者 Consumers, 商家 merchants
//        订单状态： 1下单  2商家确认 - 交换联系信息 - 自行线下交易  3商家确认交货  4买家确认收获 已完成  5用户申请取消  6商家取消 7已取消 8用户删除 9商家删除
        String model = changeOrder.getModel();
        int orderId = changeOrder.getOrderId();
        int orderStatus = changeOrder.getOrderStatus();
        if (model.equals("Consumers")){
            switch (orderStatus){
//                用户取消
                case 0: bookOrderMapper.changeOrderStatus(orderId,5);break;
                case 3: bookOrderMapper.changeOrderStatus(orderId,4);break;
                case 8: bookOrderMapper.changeOrderStatus(orderId,8);break;
            }
        }else{
            switch (orderStatus){
//                商家拒售
                case 0: bookOrderMapper.changeOrderStatus(orderId,6);break;
                case 1: bookOrderMapper.changeOrderStatus(orderId,2);break;
                case 2: bookOrderMapper.changeOrderStatus(orderId,3);break;
                case 5: bookOrderMapper.changeOrderStatus(orderId,7);break;
                case 8: bookOrderMapper.changeOrderStatus(orderId,9);break;
            }
        }


        return R.ok();
    }

    @Override
    public R getissuerInfoByOrderId(int orderId) {
        UserDto issuer=bookOrderMapper.getissuerInfoByOrderId(orderId);
        if (issuer!=null){
            return R.ok().put("issuerInfo",issuer);
        }
        return R.err();
    }

    @Override
    public R getCustomerInfoByOrderId(int orderId) {
        UserDto customerInfo=bookOrderMapper.getCustomerInfoByOrderId(orderId);
        if (customerInfo!=null){
            return R.ok().put("customerInfo",customerInfo);
        }
        return R.err();
    }

    /**
    * 根据主键删除实体对象，返回值封装成R，若成功则会把要删除的主键计入返回的R
    *
    * @param id 主键
    * @return 删除是否成功
   
    @Override
    public R removeModelById(String id){
        BookOrder model=new BookOrder();
        model.setId(id);
        return removeModelById(model);
    }
 */
    public  void setParam(QueryWrapper<BookOrder> wrapper, BookOrder model) {
        if (model == null) {
        return;
        }
//        wrapper.eq(model.getOrderId()>0,"order_id", model.getOrderId());
    }


}
